#!/usr/bin/python3

import os
import re
import zjl_util
import uapool
import time
import getopt
import sys


class dybee:
    """
    下载dybee网站电影
    """

    def __init__(self):
        # self.a = a
        # self.b = b
        # self.c = c
        self.key_value_dic = {}
        self.header = {}
        uapool.UA()
        # cookie = ("cookie", self.cookie_str)
        # headers = [cookie]
        # uapool.set_header(headers)

    def set_header(self, header_file_path, m3u8_url):
        if not os.path.exists(header_file_path):
            print('[warn] file: ' + header_file_path + ' not exist')
            return
        header = {}
        with open(header_file_path, 'r') as h_file:
            while h_file.readable():
                line = h_file.readline()
                sp = line.split(': ')
                if line == '':
                    break
                if len(sp) == 2:
                    k = sp[0]
                    v = sp[1]
                    header[k] = v
        host = uapool.get_base_url(m3u8_url).replace('https://', '').replace('http://', '')
        header['Host'] = host
        if ':authority' in header:
            header[':authority'] = host
        self.header = header
        # print(self.header)

    def down_file(self, m3u8_url, dir_path, file_name):
        ts_list = self.get_ts_list(m3u8_url, dir_path, file_name)
        ts_file_paths = []
        ts_path = ''
        for i in ts_list:
            ts_url = ''
            if str(i).startswith('/'):
                ts_url = uapool.get_base_url(m3u8_url) + '/' + i
            else:
                r_index = m3u8_url.rindex('/')
                ts_url = m3u8_url[0: r_index + 1] + i
            ts_path = dir_path + "/" + file_name.replace('.ts', '')
            splits = i.split('/')
            ts_file_name = splits[len(splits) - 1]
            self.down_ts(ts_url, ts_path, ts_file_name)
            ts_file_paths.append(ts_path + '/' + ts_file_name)
        result_file_path = dir_path + "/" + file_name
        zjl_util.merge_ts(ts_file_paths, result_file_path)
        # '''删除已合并源文件'''
        # for p in ts_file_paths:
        #     os.remove(p)
        # if os.path.exists(ts_path):
        #     os.rmdir(ts_path)

    def get_ts_list(self, m3u8_url, dir_path: None, file_name: None):
        doc = zjl_util.get_doc3(m3u8_url, self.header)
        print(doc)

        if dir_path is not None and file_name is not None:
            """ 保存m3u8内容 """
            p = dir_path + "/" + file_name.replace('.ts', '')
            if not os.path.exists(p):
                os.makedirs(p)
            m3u8_path = p + '/index.m3u8'
            with open(m3u8_path, 'w') as f:
                f.write(doc)

        pat_ts = '(.*?\.ts)'
        ts_list = re.compile(pat_ts).findall(doc)
        return ts_list

    def down_ts(self, ts_url, dir_path, file_name):
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)
        i = 0
        redo_count = 0  # 用于记录下载出现错误是记录重试次数，顺利下载完后，次数归0
        while redo_count < 5:
            file_path = dir_path + "/" + file_name
            try:
                zjl_util.download(ts_url, file_path)
                return
            except Exception as e:
                print("request error url:" + ts_url)
                print(e)
                print('-------\t重试下载  ' + ts_url + '  \t-------')
                redo_count += 1
                time.sleep(redo_count * 30 + 1) # 每次重试增加时间
                # 提前结束本次循环，再次下载这一章
                if redo_count >= 5:
                    print('[error] 多次重试后失败')
                    exit()


def main():
    d = dybee()
    m3u8_url = 'https://youku.com-youku.net/20180616/12510_f998498f/1000k/hls/index.m3u8'
    dir_path = 'E:/FavoriteVideo'
    file_name = '出包王女第二季无修_01.ts'
    header_file_path = 'D:/test/film/header.conf'

    opts, args = getopt.getopt(sys.argv[1:], "hu:d:f:H:")
    for o, a in opts:
        if o == '-h':
            print("python3 down_dybee_film.py -u " + m3u8_url + " -d " + dir_path + " -f " + str(file_name) + " -H " + str(header_file_path))
            exit()
        if o == '-u':
            m3u8_url = a
        if o == '-d':
            dir_path = a
        if o == '-f':
            file_name = a
        if o == '-H':
            header_file_path = a
    print('m3u8地址：' + m3u8_url)
    print('保存路径：' + dir_path + '/' + file_name)

    d.set_header(header_file_path, m3u8_url)
    d.down_file(m3u8_url, dir_path, file_name)


if __name__ == "__main__":
    main()
